var express = require('express');
var router = express.Router();
var uuid = require('uuid').v1;


router.get('/cache', async function (req, res, next) {
    var projectId = req.query.projectId;
    var Sql = `SELECT * FROM project_cache WHERE project_id = ? AND disable = 0`;
    try {
        var vals = await asyncQuery(Sql, [projectId]);
        res.json(vals);
    } catch (error) {
         next(error)
    };
});

router.post('/cache', async function (req, res, next) {
    var cacheId = uuid();
    var data = {
        cache_id: cacheId,
        project_id: req.body.projectId,
        value: req.body.value,
        key: req.body.key,
        name: req.body.name,
        disable: 0,
    };

    var Sql = `INSERT INTO project_cache SET ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, data);
        res.json({
            id: cacheId
        });
    } catch (error) {
         next(error)
    };
})


router.put('/cache', async function (req, res, next) {
    var cacheId = req.body.cacheId;
    var data = {
        value: req.body.value,
        key: req.body.key,
    };

    var Sql = `UPDATE project_cache SET ? WHERE cache_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [data, cacheId]);
        res.json({});
    } catch (error) {
         next(error)
    };
});





router.delete('/cache', async function (req, res, next) {
    var cacheId = req.body.cacheId;
    var Sql = `UPDATE project_cache SET disable = 1 WHERE cache_id = ?`;
    try {
        await Permission.CPP(req.headers.token,  req.query.projectId);
        await asyncQuery(Sql, [cacheId]);
        res.json({});
    } catch (error) {
         next(error)
    };
});




module.exports = router;